package com.xm.transfer.factory;

import com.xm.transfer.annotations.Autowired;
import com.xm.transfer.annotations.Component;
import com.xm.transfer.utils.TransactionManager;
import net.sf.cglib.proxy.*;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;

@Component
public class ProxyFactory {

    private static ProxyFactory proxyFactory = new ProxyFactory();

    @Autowired
    private TransactionManager transactionManager;

    public static ProxyFactory getInstance() {
        if (null == proxyFactory) {
            synchronized (ProxyFactory.class) {
                if (null == proxyFactory) {
                    proxyFactory = new ProxyFactory();
                }
            }
        }
        return proxyFactory;
    }

    public <E> E getCglibProxy(Object obj) {
        return (E) Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                return transaction(obj, method, args);
            }
        });
    }

    public <E> E getJDKProxy(Object obj) {
        return (E) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
               return transaction(obj, method, args);
            }
        });
    }

    private Object transaction(Object obj, Method method, Object[] args) throws SQLException {
        Object result = null;
        try {
            transactionManager.enableTransaction();
            result = method.invoke(obj, args);
            // 提交事务
            transactionManager.commitTransaction();
        } catch (Exception e) {
            // 回滚事务
            transactionManager.rollbackTransaction();
            e.printStackTrace();
        }
        return result;
    }
}
